import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: '',
    base_id: null, // 当前选择的基地 ID
  },
  mutations: {
    set_token(state, token) { 
      state.token = token;
      sessionStorage.setItem('token', token);
    }, 
    del_token(state) { 
      state.token = ''; 
      sessionStorage.removeItem('token'); 
    },
    setBaseId(state, base_id) {
      state.base_id = base_id;
      sessionStorage.setItem('base_id', base_id); // 持久化 base_id
    },
    clearBase(state) {
      state.base_id = null;
      sessionStorage.removeItem('base_id');
    }
  },
  actions: {
    updateBaseId({ commit }, base_id) {
      commit('setBaseId', base_id);
    },
    initializeStore({ commit }) {
      const token = sessionStorage.getItem('token');
      const base_id = sessionStorage.getItem('base_id');
      
      if (token) {
        commit('set_token', token);
      }
      
      if (base_id) {
        commit('setBaseId', parseInt(base_id, 10));
      }
    }
  },
  getters: {
    getBaseId: (state) => state.base_id,
  },
  modules: {
    // 如果有其他模块，可以在这里添加
  }
});